import json

from flask import Flask
from flask_apscheduler import APScheduler
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_cors import CORS
import logging
from app import resources
from app.commons.config import build_env_mysql, Config


def get_config():
    with open("config.json") as CONFIG:
        return json.load(CONFIG)


def create_app():
    app = Flask(__name__, instance_relative_config=True)
    local_config = get_config()
    app.config.from_object(Config)

    app.config.from_mapping(build_env_mysql(local_config["mysql"]))

    db = SQLAlchemy(app)
    db.init_app(app)
    Migrate(app, db)

    # scheduler=APScheduler()
    # scheduler.init_app(app)
    # scheduler.start()

    CORS(app, supports_creadentials=True)
    logging.basicConfig(level=logging.WARN, filename='info.log', filemode='a',
                        format='%(asctime)s - %(levelname)s: %(message)s')
    logging.warning("Server Starting...")
    # register API
    app.register_blueprint(resources.admin_blueprint, url_prefix="/")
    app.register_blueprint(resources.login_blueprint, url_prefix="/")
    app.register_blueprint(resources.testapi_blueprint, url_prefix="/api")
    app.register_blueprint(resources.file_streaming_blueprint, url_prefix="/api")
    app.register_blueprint(resources.list_blueprint, url_prefix="/api")
    app.register_blueprint(resources.upload_config_blueprint, url_prefix="/api")
    app.register_blueprint(resources.csgostock_blueprint, url_prefix="/api")
    return app
